#include "mqtt.h"

#define DEBUG_ON 0

WiFiClient espClient;
PubSubClient client(espClient);
extern "C" void Pub_Info(char* a){
  client.publish(config_info.pub_topic,a);
}

void reconnect()
{
  // Loop until we're reconnected
  while (!client.connected()) {
#if DEBUG_ON
    Serial.println("Attempting MQTT connection...");
#endif
    if (client.connect(config_info.device_id, config_info.user_name, config_info.user_psss)) {
#if DEBUG_ON
      Serial.println("connected");
#endif
      client.subscribe(config_info.sub_topic);
#if DEBUG_ON
      Serial.println("subscribe:");
      Serial.println(config_info.sub_topic);
#endif
      break;
    } else {
#if DEBUG_ON
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
#endif
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void(* resetFuncti) (void) = 0;
void callback(char* topic, byte* payload, unsigned int length) {
  char flag = 0;
  char message[101];
  memset(message, 0, 101);
  for (int i = 0; i < length; i++) {
    message[i] = (char)payload[i];
    if(message[i]=='R')flag++;
    //Serial.print((char)payload[i]);
  }
  if(flag>=51)
  {
    config_file_remove();
    resetFuncti();
  }
  else
  Serial.println(message);
}
extern "C" void mqtt_init(void)
{
  client.setServer(config_info.server_ip,atoi(config_info.server_port));
  client.setCallback(callback);
  client.connect(config_info.device_id, config_info.user_name, config_info.user_psss);
  client.subscribe(config_info.sub_topic);
  #if DEBUG_ON
  Serial.println(WiFi.localIP());
  #endif
}
extern "C" void  mqtt_loop(void)
{
if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
